package tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;

    public TcpEchoClient(String severIp, int severPort) throws IOException {
        socket = new Socket(severIp, severPort);
    }

    public void start() {
        System.out.println("客户端启动");
        try (InputStream inputStream = socket.getInputStream();
             OutputStream outputStream = socket.getOutputStream()) {
            //从控制台输入
            Scanner sc = new Scanner(System.in);
            //从网络中输入,用于接收服务器端的响应
            Scanner scNet = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while (true) {
                //1.从控制台读取用户输入
                String request = sc.next();
                //2.向服务器发送请求
                writer.println(request);
                //刷新缓冲区
                writer.flush();
                //3.接收服务器返回的响应
                String response = scNet.next();
                //4.打印响应
                System.out.println(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1", 9090);
        tcpEchoClient.start();
    }
}
